<?php

namespace App\Http\Middleware;

use App\Models\ManagerLog;
use Closure;
use Illuminate\Http\Request;

class RequestManagerLogs
{
    private array $ignoreRoutes = [
        'api.*',
        'wechat.*',
        'login',
        'node.index',
    ];

    /**
     * @param Request $request
     * @return bool
     */
    private function shouldInsert(Request $request): bool
    {
        if ($request->is('*/real-time-data/*')) return false;
        if ($request->routeIs($this->ignoreRoutes)) return false;
        return true;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (!$this->shouldInsert($request)) return $next($request);

        $input = $request->all();

        $data = [
            'method'  => $request->method(),
            'ip'      => $request->getClientIp(),
            'input'   => json_encode($input),
            'user_id' => auth()->user()->id ?? 0,
            'path'    => substr($request->path(), 0, 255),
        ];

        try {
            // todo 定时插入 && 到数量后插入
            ManagerLog::Create($data);
        } catch (\Exception $e) {
            report($e);
            info(__METHOD__, is_array($input) ? $input : [$input]);
        }
        return $next($request);
    }
}
